package com.yoku.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.Executors;

/**
 * Desc:
 * Date: 2016/12/26
 */
@Configuration
@EnableAutoConfiguration
public class UserAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public ObjectMapper objectMapper(){
        return new ObjectMapper();
    }

    @Bean
    @ConditionalOnMissingBean
    public EventBus eventBus(){
        return new AsyncEventBus(Executors.newFixedThreadPool(5));
    }

    @Bean
    public Client transportClient(){
        try {

            ClassLoader classLoader = new ClassLoader() {
                @Override
                public Class<?> loadClass(String name) throws ClassNotFoundException {
                    return super.loadClass(name);
                }
            };
            Settings settings = Settings.settingsBuilder()
                    .put("cluster.name", "yoku").put("client.transport.sniff", false).build();
            Client client = TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
            return client;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }
    }
}
